using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Data.Linq;

public partial class Home_ImportStudentData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnImportStudents_Click(object sender, EventArgs e)
    {
        //Check if there is a file
        if (fileupStudentList.HasFile)
        {
            //Get the file extension
            string fileExt = System.IO.Path.GetExtension(fileupStudentList.FileName);
            //Check that this is an excel file
            if (fileExt == ".xls")
            {
                try
                {
                    TextBox1.Text = "";
                    this.Session.Add("ImportRowCounter", 0);
                    this.Session.Add("ImportInserted", 0);
                    this.Session.Add("ImportUpdated", 0);
                    this.Session.Add("ImportUnProcessed", 0);
                    this.Session.Add("Number", 0);
                    fileupStudentList.SaveAs(Server.MapPath("../studentImport") + "\\StudentData.xls");
                    this.lblMessage.Text = "Success";

                    //Enable buttons
                    btnPause.Visible = true;
                    btnResume.Visible = true;
                    TextBox1.Visible = true;
                    lblErrors.Visible = true;

                    //Enable the timer which starts processing each row one by one with the gap of 1 ms.
                    ImportTimer.Enabled = true;
                    this.btnImportStudents.Enabled = false;
                }
                catch (Exception ex)
                {
                    this.lblMessage.Text = "Error: " + ex.Message.ToString();
                }
            }
            else
            {
                this.lblMessage.Text = "Only xls files allowed.";
            }
        }
        else
        {
            this.lblMessage.Text = "You have not selected a file.";
        }
    }


    protected void ImportTimer_Tick(object sender, EventArgs e)
    {
        ProcessStudentDataImport();
    }

    /// <summary>
    /// This method returns students datatable by using oledb connection to the dataset.
    /// </summary>
    /// <returns></returns>
    protected DataTable GetStudentDataTable()
    {
        string sFilePath = Server.MapPath("../studentImport") + "\\StudentData.xls";
        string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFilePath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";


        OleDbConnection oledbConn = new OleDbConnection(conn);
        OleDbCommand cmd1 = new OleDbCommand("SELECT *  FROM [Sheet1$]", oledbConn);
        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
        objAdapter1.SelectCommand = cmd1;
        DataSet dsStudents = new DataSet();
        objAdapter1.Fill(dsStudents, "StudentData");

        return dsStudents.Tables[0];
    }


    protected void ProcessStudentDataImport()
    {
        //Check if session variables exist and import is not stopped
        if (Session["ImportRowCounter"] == null)
            return;

        //check if the file exits 
        // Check only once as we are storing the datatable in the 
        // session object the very first time
        if (((int)Session["ImportRowCounter"]) == 0)
        {
            if (File.Exists(Server.MapPath("../studentImport") + "\\StudentData.xls"))
            {
                if (Session["ImportDataTable"] == null)
                {
                    //We add student datatable as the session variable so that when this method is called by the timer
                    //than we don't have to access excel file again.
                    Session.Add("ImportDataTable", GetStudentDataTable());
                }
            }
            else
            {
                this.lblMessage.Text = "There was a problem finding the import file";
            }
        }

        //No more rows are left in the datatable
        if (((DataTable)Session["ImportDataTable"]).Rows.Count == (int)Session["ImportRowCounter"])
        {
            lblMessage.Text = "Import Complete!" + Session["Number"].ToString();
            //Stop the import and hide the pause and resume buttons
            btnStop_Click(null, null);
            return;
        }




        //Now we will get the datarow to be processed using the counter we keep track in session variable. 
        //This datarow is processed and finally details are uptaded through ajax panel
        DataRow dr = ((DataTable)Session["ImportDataTable"]).Rows[(int)Session["ImportRowCounter"]];


        //******* Testing Purposes Only****************
        //DataTable dt = (DataTable)Session["ImportDataTable"];
        //if ((int)Session["ImportRowCounter"] == 0)
        //    dt.Columns.Add("ProcessedMessage");
        //GridView1.DataSource = ((DataTable)Session["ImportDataTable"]).DefaultView;
        //GridView1.DataBind();

        try
        {
            string studentId = dr[0].ToString();

            MembershipUser m = Membership.GetUser(studentId);
            if (m != null)//Student already exists as a system user
            {
                UpdateUserDetails(dr);

                //Increase the counter for updated records
                Session["ImportUpdated"] = (int)Session["ImportUpdated"] + 1;
            }
            else //Student does not exist as a system user
            {
                InsertNewUser(dr);
                //Increase the counter for inserted records.
                Session["ImportInserted"] = (int)Session["ImportInserted"] + 1;
            }

            //Now all of the students should exist in the system and we can update their unit enrolments
            UpdateUnitEnrolments(dr);
        }
        catch (Exception e)
        {
            //Excel has a header so +2
            TextBox1.Text += Environment.NewLine + "Excel " + ((int)Session["ImportRowCounter"] + 2).ToString() + ": " + dr[2].ToString() + " " + dr[3].ToString() + "  " + e.Message;
            Session["ImportUnProcessed"] = (int)Session["ImportUnProcessed"] + 1;
            lblUnprocessed.Text = "Unprocessed: " + Session["ImportUnProcessed"].ToString();
            updtPnlUnProcessed.Update();
        }
        finally
        {
            //Update the import detals
            this.lblProcessed.Text = "Processing row: " + Session["ImportRowCounter"].ToString();
            this.lblInserted.Text = "Inserted: " + Session["ImportInserted"].ToString();
            this.lblUpdated.Text = "Updated: " + Session["ImportUpdated"].ToString();
            updtPnlImportData.Update();
            //Increase the coumnter
            Session["ImportRowCounter"] = (int)Session["ImportRowCounter"] + 1; ;
        }
    }

    #region "Insert/update"
    protected void UpdateUserDetails(DataRow dr)
    {
        string studentId = dr[0].ToString();
        string email = dr[7].ToString();
        string address1 = dr[8].ToString();
        string city = dr[9].ToString();
        string givenNames = dr[2].ToString();
        string lastName = dr[3].ToString();
        string courseCode = dr[4].ToString();
        string campusCode = dr[5].ToString();
        string stateAbbrev = dr[10].ToString();
        string countryName = dr[12].ToString();
        string postCode = dr[11].ToString();
        string mobilePhone = dr[15].ToString();

        MembershipUser m = Membership.GetUser(studentId);
        //We need to update their address, campus and course enrolments 
        //Start with their address
        //Get the userid for the username

        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        User user = (from u in db.Users
                     where u.UserName == studentId
                     select u).ToList<User>().First<User>();

        user.DateUpdated = DateTime.Now;
        user.FirstName = givenNames;
        user.IsActive = true;
        user.LastName = lastName;
        user.UpdatedBy = User.Identity.Name;

        ////*************//
        ////Need to do some checking here cos we don't want to be going off to Google
        ////for every address if it hasn't changed
        ////*************//

        ////Update the address details
        int countryId = new PlacementManager.Geo_CountryComponent().GetCountryIdWCountryName(countryName);
        int stateId = new PlacementManager.Geo_AdministrativeDivisionComponent().GetAdministrativeDivisionId(stateAbbrev);

        if (countryId > 0 && stateId > 0) //we have found both a matching state and country so we can do the address insert
        {
            //Let's try and get the coordinates

            //A Google Map object so we can try and resolve the coordiantes of the student's address
            PlacementManager.GoogleMap oGM = new PlacementManager.GoogleMap();

            string address = address1 + ", " + city + ", " + stateAbbrev + ", " + countryName;

            List<Address> addresses = (from a in db.Addresses
                                       join ua in db.UserAddresses on a.AddressId equals ua.AddressId
                                       where ua.UserId == user.UserId
                                       && ua.IsPrimary == true
                                       select a).ToList<Address>();

            //Check if user is found and if address couldnot be found
            if (addresses.Count >= 1)
            {
                Address add = addresses.First<Address>();
                //if (!(add.Address1.Trim().ToUpper() == address1.Trim().ToUpper()
                //    && add.City.Trim().ToUpper() == city.Trim().ToUpper()
                //    && add.StateId == stateId && add.CountryId == countryId))
                //{
                    add.Address1 = address1;
                    add.Address2 = String.Empty;
                    add.City = city;
                    add.CountryId = countryId;
                    if (add.Longitude == 0)
                    {
                        //Address is changed so find out the new coordinates
                     //   float[] coordinates = oGM.GetLongitudeLatitude(address);
                       // if (!(coordinates[0] == 0))
                            Session["Number"] = (int)Session["Number"] + 1;

                     //   add.Longitude = coordinates[0];
                     //   add.Latitude = coordinates[1];
                    }
                    add.CreatedBy = User.Identity.Name;
                    add.DateCreated = DateTime.Now;
                    add.DateUpdated = DateTime.Now;
                    add.IsActive = true;
                    add.IsPostal = true;
                    add.StateId = stateId;
                    add.UpdatedBy = User.Identity.Name;
                    add.PostCode = postCode;
                    db.SubmitChanges();
                //}

                //Make the address primary
                UserAddress ua = (from u in db.UserAddresses
                                  where u.UserId == user.UserId
                                  select u).ToList<UserAddress>()[0];

                ua.IsPrimary = true;
                ua.DateUpdated = DateTime.Now;
                ua.UpdatedBy = User.Identity.Name;
                db.SubmitChanges();
            }
            else
            {
                //New Address
                Address newAdd = new Address();
                newAdd.Address1 = address1;
                newAdd.Address2 = String.Empty;
                newAdd.City = city;
                newAdd.Street = "";
                newAdd.CountryId = countryId;

                if (newAdd.Longitude == 0)
                {
                    float[] coordinates = oGM.GetLongitudeLatitude(address);
                    if (!(coordinates[0] == 0))
                        Session["Number"] = (int)Session["Number"] + 1;
                    newAdd.Longitude = coordinates[0];
                    newAdd.Latitude = coordinates[1];
                }
                else
                {
                    newAdd.Longitude = 0;
                    newAdd.Latitude = 0;
                }
                newAdd.CreatedBy = User.Identity.Name;
                newAdd.DateCreated = DateTime.Now;
                newAdd.DateUpdated = DateTime.Now;
                newAdd.IsActive = true;
                newAdd.IsPostal = true;
                newAdd.StateId = stateId;
                newAdd.UpdatedBy = User.Identity.Name;
                newAdd.PostCode = postCode;

                //Create a link
                UserAddress ua = new UserAddress();
                ua.UserId = user.UserId;
                ua.IsActive = true;
                ua.IsPrimary = true;
                ua.IsCurrent = true;
                ua.DateCreated = DateTime.Now;
                ua.DateUpdated = DateTime.Now;
                ua.UpdatedBy = User.Identity.Name;
                ua.CreatedBy = User.Identity.Name;
                newAdd.UserAddresses.Add(ua);

                db.Addresses.InsertOnSubmit(newAdd);

                db.SubmitChanges();
            }
        }
        else //When state/Country is not found in the system
        {

            string address = address1 + ", " + city + ", " + stateAbbrev + ", " + countryName;

            List<Address> addresses = (from a in db.Addresses
                                       join ua in db.UserAddresses on a.AddressId equals ua.AddressId
                                       where ua.UserId == user.UserId
                                       && ua.IsPrimary == true 
                                       select a).ToList<Address>();

            //Check if user is found and if address couldnot be found
            if (addresses.Count >= 1)
            {
                Address add = addresses.First<Address>();
                if (!(add.Address1.Trim().ToUpper() == address1.Trim().ToUpper()
                    && add.City.Trim().ToUpper() == city.Trim().ToUpper()
                    && add.StateId == stateId && add.CountryId == countryId))
                {
                    //Address is changed so find out the new coordinates
                    add.Address1 = address1;
                    add.Address2 = String.Empty;
                    add.City = city;
                    add.CountryId = countryId;
                    //We don't want to use google maps as state or country is unknown.
                    add.Longitude = 0;
                    add.Latitude = 0;
                    add.CreatedBy = User.Identity.Name;
                    add.DateCreated = DateTime.Now;
                    add.DateUpdated = DateTime.Now;
                    add.IsActive = true;
                    add.IsPostal = true;
                    add.StateId = 66263;
                    add.UpdatedBy = User.Identity.Name;
                    add.PostCode = postCode;
                    db.SubmitChanges();

                    UserAddress ua = (from u in db.UserAddresses
                                      where u.UserId == user.UserId
                                      select u).ToList<UserAddress>()[0];

                    ua.IsPrimary = true;
                    ua.DateUpdated = DateTime.Now;
                    ua.UpdatedBy = User.Identity.Name;
                    db.SubmitChanges();
                }
            }
            else
            {
                //New Address
                Address newAdd = new Address();
                newAdd.Address1 = address1;
                newAdd.Address2 = String.Empty;
                newAdd.City = city;
                newAdd.Street = "";
                newAdd.CountryId = countryId; 
                //We don't want to use google maps as state or country is unknown.
                newAdd.Longitude = 0;
                newAdd.Latitude = 0;
                newAdd.CreatedBy = User.Identity.Name;
                newAdd.DateCreated = DateTime.Now;
                newAdd.DateUpdated = DateTime.Now;
                newAdd.IsActive = true;
                newAdd.IsPostal = true;

                //"Foreign State"
                newAdd.StateId = 66263;
                newAdd.UpdatedBy = User.Identity.Name;
                newAdd.PostCode = postCode;

                //Create a link
                UserAddress ua = new UserAddress();
                ua.UserId = user.UserId;
                ua.IsActive = true;
                ua.IsPrimary = true;
                ua.IsCurrent = true;
                ua.DateCreated = DateTime.Now;
                ua.DateUpdated = DateTime.Now;
                ua.UpdatedBy = User.Identity.Name;
                ua.CreatedBy = User.Identity.Name;
                newAdd.UserAddresses.Add(ua);

                db.Addresses.InsertOnSubmit(newAdd);

                db.SubmitChanges();
            }
        }

        //Update the campus code in the Likstudentcampus table
        this.UpdateStudentCampusLink(studentId, campusCode);
        //See if the course id/username combo exists in the link table
        this.UpdateStudentCourseLink(studentId, courseCode);

    }
    protected void InsertNewUser(DataRow dr)
    {
        string studentId = dr[0].ToString();
        string email = dr[7].ToString();
        string address1 = dr[8].ToString();
        string city = dr[9].ToString();
        string givenNames = dr[2].ToString();
        string lastName = dr[3].ToString();
        string courseCode = dr[4].ToString();
        string campusCode = dr[5].ToString();
        string stateAbbrev = dr[10].ToString();
        string countryName = dr[12].ToString();
        string postCode = dr[11].ToString();
        string mobilePhone = dr[15].ToString();

        //Create user account
        MembershipCreateStatus mcStatus;
        string password = Membership.GeneratePassword(6, 2);
        Membership.CreateUser(studentId, password, email, "Your postcode", postCode, true, out mcStatus);
        Roles.AddUserToRole(studentId, "PM_Student");

        //Now create a record in the User table
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        User us = new User();
        us.FirstName = givenNames;
        us.LastName = lastName;
        us.IdNumber = studentId;
        us.IsActive = true;
        us.DateCreated = DateTime.Now;
        us.DateUpdated = DateTime.Now;
        us.CreatedBy = User.Identity.Name;
        us.UpdatedBy = User.Identity.Name;
        us.UserName = studentId;

        db.Users.InsertOnSubmit(us);
        db.SubmitChanges();

        int userId = us.UserId;

        //Now create an address record
        int countryId = new PlacementManager.Geo_CountryComponent().GetCountryIdWCountryName(countryName);
        int stateId = new PlacementManager.Geo_AdministrativeDivisionComponent().GetAdministrativeDivisionId(stateAbbrev);

        if (countryId > 0 && stateId > 0) //we have found both a matching state and country so we can do the address insert
        {

            //Let's try and get the coordinates
            string address = address1 + ", " + city + ", " + stateAbbrev + ", " + countryName;

            //A Google Map object so we can try and resolve the coordiantes of the student's address
            PlacementManager.GoogleMap oGM = new PlacementManager.GoogleMap();
            float[] coordinates = oGM.GetLongitudeLatitude(address);

            if (!(coordinates[0] == 0))
                Session["Number"] = (int)Session["Number"] + 1;
            Address add = new Address();
            add.Address1 = address1;
            add.Address2 = String.Empty;
            add.City = city;
            add.CountryId = countryId;
            add.Longitude = coordinates[0];
            add.Latitude = coordinates[1];
            add.CreatedBy = User.Identity.Name;
            add.DateCreated = DateTime.Now;
            add.DateUpdated = DateTime.Now;
            add.IsActive = true;
            add.IsPostal = true;
            add.StateId = stateId;
            add.UpdatedBy = User.Identity.Name;

            db.Addresses.InsertOnSubmit(add);

            db.SubmitChanges();

            int addressId = add.AddressId;

            //Now create the link between address and user
            UserAddress ua = new UserAddress();
            ua.AddressId = addressId;
            ua.CreatedBy = User.Identity.Name;
            ua.DateCreated = DateTime.Now;
            ua.DateUpdated = DateTime.Now;
            ua.IsActive = true;
            ua.IsPrimary = true;
            ua.UpdatedBy = User.Identity.Name;
            ua.UserId = userId;

            db.UserAddresses.InsertOnSubmit(ua);

            db.SubmitChanges();
        }
        else
        { //Let's try and get the coordinates
            string address = address1 + ", " + city + ", " + stateAbbrev + ", " + countryName;

            //A Google Map object so we can try and resolve the coordiantes of the student's address
            PlacementManager.GoogleMap oGM = new PlacementManager.GoogleMap();
            float[] coordinates = oGM.GetLongitudeLatitude(address);

            if (!(coordinates[0] == 0))
                Session["Number"] = (int)Session["Number"] + 1;
            Address add = new Address();
            add.Address1 = address1;
            add.Address2 = String.Empty;
            add.City = city;
            add.CountryId = countryId;
            add.Longitude = coordinates[0];
            add.Latitude = coordinates[1];
            add.CreatedBy = User.Identity.Name;
            add.DateCreated = DateTime.Now;
            add.DateUpdated = DateTime.Now;
            add.IsActive = true;
            add.IsPostal = true;

            //To Do:-
            //Set stateId to 6623 (Forign State)
            // Would need a change on production
            add.StateId = 6623;
            add.UpdatedBy = User.Identity.Name;

            db.Addresses.InsertOnSubmit(add);

            db.SubmitChanges();

            int addressId = add.AddressId;

            //Now create the link between address and user
            UserAddress ua = new UserAddress();
            ua.AddressId = addressId;
            ua.CreatedBy = User.Identity.Name;
            ua.DateCreated = DateTime.Now;
            ua.DateUpdated = DateTime.Now;
            ua.IsActive = true;
            ua.IsPrimary = true;
            ua.UpdatedBy = User.Identity.Name;
            ua.UserId = userId;

            db.UserAddresses.InsertOnSubmit(ua);

            db.SubmitChanges();
        }

        //Now create a link between the student user and the campus of enrollment
        this.InsertStudentCampusLink(studentId, campusCode);

        //Now create a link with the course that the user is enrolled in
        this.InsertStudentCourseLink(studentId, courseCode);

        //Now create a link with the division
        this.InsertStudentDivisionLink(studentId);
    }
    protected void UpdateUnitEnrolments(DataRow dr)
    {
        string studentId = dr[0].ToString();
        //Make sure they do actually exist
        MembershipUser m = Membership.GetUser(studentId);
        if (m != null)//Student already exists as a system user
        {
            studentId = dr[0].ToString();
            string unitCode = dr[6].ToString();

            PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
            List<Unit> unitList = (from u in db.Units
                                   where u.UnitCode == unitCode
                                   select u).ToList<Unit>();

            //Return if we cannot find Unit in the system
            //This is because we are only bothered about the placement system units and we don't need to insert not found unit.
            Unit unit;
            if (unitList.Count > 0)
            {
                unit = unitList[0];
            }
            else
            {
                return;
            }

            //Update the LinkStudentUnit table to show currently enolled = false for all links
            int? errorCode = 0;
            db.pr_LinkStudentUnit_DAL_UnEnrolWUsername(studentId, ref errorCode);

            //Now for see if the association between the student and the unit exists
            InsertUpdateStudentUnit(unit.UnitId, studentId);

        }
    }
    #endregion

    private void InsertUpdateStudentUnit(int unitId, string userName)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        //Now for see if the association between the student and the unit exists
        List<StudentUnit> suList = (from su in db.StudentUnits
                                    join u in db.Users on su.UserId equals u.UserId
                                    where su.UnitId == unitId
                                    && u.UserName == userName
                                    select su).ToList<StudentUnit>();
        if (suList.Count > 0)
        {
            StudentUnit su = suList.First<StudentUnit>();

            su.DateUpdated = DateTime.Now;
            su.UpdatedBy = User.Identity.Name;
            su.IsCurrentlyEnrolled = true;
            db.SubmitChanges();
        }
        else
        {//Else insert a new association and set its current enrolment status to true
            if (unitId > 0)
            {
                //First get the userid from the users table.
                User user = (from u in db.Users
                          where u.UserName == userName
                          select u).ToList<User>()[0];


                StudentUnit newStudentUnit = new StudentUnit();
                newStudentUnit.UnitId = unitId;
                newStudentUnit.CreatedBy = User.Identity.Name;
                newStudentUnit.DateCreated = DateTime.Now;
                newStudentUnit.UpdatedBy = User.Identity.Name;
                newStudentUnit.DateUpdated = DateTime.Now;

                newStudentUnit.IsActive = true;
                newStudentUnit.IsCurrentlyEnrolled = true;
                newStudentUnit.UserId = user.UserId;
                db.StudentUnits.InsertOnSubmit(newStudentUnit);

                db.SubmitChanges();
            }
        }

    }


    /// <summary>
    /// This method is written as some if the the child control could not be found using findcontrol.
    /// Might be a bug.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    private Control Find(Control control, string id)
    {
        if (control.ID == id)
        {
            return control;
        }
        foreach (Control child in control.Controls)
        {
            Control result = this.Find(child, id);
            if (result != null)
            {
                return result;
            }
        }
        return null;
    }

    protected void InsertStudentCampusLink(string userName, string campusCode)
    {
        int campusId = new PlacementManager.CampusComponent().GetCampusIdWCampusCode(campusCode);

        if (campusId > 0) //Then we have found a matching campus so we can do the insert
        {
            PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
            StudentCampus sc = new StudentCampus();
            sc.CampusId = campusId;
            sc.UserName = User.Identity.Name;
            sc.IsActive = true;
            sc.IsCurrentlyEnrolled = true;
            sc.CreatedBy = User.Identity.Name;
            sc.DateCreated = DateTime.Now;
            sc.UpdatedBy = User.Identity.Name;
            sc.DateUpdated = DateTime.Now;

            db.StudentCampus.InsertOnSubmit(sc);
            db.SubmitChanges();
        }
    }

    protected void UpdateStudentCampusLink(string userName, string campusCode)
    {
        //Get CampusId through Campus Code.
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        List<Campus> campusList = (from camp in db.Campus
                                   where camp.CampusCode == campusCode
                                   select camp).ToList<Campus>();

        if (campusList.Count > 0) //Then we have found a matching campus so we can do the insert
        {
            int? errorCode = 4;
            db.pr_LinkStudentCampus_DAL_UpdateEnrolledCampus(userName, campusList[0].CampusId, User.Identity.Name, ref errorCode);
        }
    }

    protected void InsertStudentCourseLink(string userName, string courseCode)
    {
        //Get Course Id
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        List<Course> courseList = (from c in db.Courses
                                   where c.CourseCode == courseCode
                                   select c).ToList<Course>();


        if (courseList.Count > 0) //then we have found a matching course so we can do the insert
        {
            StudentCourse sc = new StudentCourse();
            sc.CourseId = courseList[0].CourseId;
            sc.IsActive = true;
            sc.IsCurrentlyEnrolled = true;
            sc.UserName = userName;
            sc.CreatedBy = User.Identity.Name;
            sc.DateCreated = DateTime.Now;
            sc.UpdatedBy = User.Identity.Name;
            sc.DateUpdated = DateTime.Now;

            db.StudentCourses.InsertOnSubmit(sc);
            db.SubmitChanges();
        }
    }

    protected void UpdateStudentCourseLink(string userName, string courseCode)
    {
        //Get CampusId through Campus Code.
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        List<Course> courseList = (from c in db.Courses
                                   where c.CourseCode == courseCode
                                   select c).ToList<Course>();

        //Crash/Error Handling
        if (courseList.Count == 0)
            return;

        int? errorCode = 4;
        db.pr_LinkStudentCourse_DAL_UpdateEnrolledCourse(userName, courseList[0].CourseId, User.Identity.Name, ref errorCode);
    }

    protected void InsertStudentDivisionLink(string userName)
    {
        if (Session["DivisionId"] != null)
        {
            PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
            UserDivision ud = new UserDivision();
            ud.DivisionId = Int32.Parse(Session["DivisionId"].ToString());
            ud.UserName = userName;
            ud.IsActive = true;
            ud.CreatedBy = User.Identity.Name;
            ud.DateCreated = DateTime.Now;
            ud.UpdatedBy = User.Identity.Name;
            ud.DateUpdated = DateTime.Now;

            db.UserDivisions.InsertOnSubmit(ud);
            db.SubmitChanges();
        }
    }
    protected void btnPause_Click(object sender, EventArgs e)
    {
        if (ImportTimer.Enabled)
            ImportTimer.Enabled = false;
    }
    protected void btnResume_Click(object sender, EventArgs e)
    {
        if (!ImportTimer.Enabled)
            ImportTimer.Enabled = true;
    }
    protected void btnStop_Click(object sender, EventArgs e)
    {
        ImportTimer.Enabled = false;
        btnPause.Visible = false;
        btnResume.Visible = false;
        lblErrors.Visible = false;
        btnImportStudents.Enabled = true;
        updtPnlImportData.Update();

        //Remove all the session variables as they would not be needed.
        this.Session.Remove("ImportRowCounter");
        this.Session.Remove("ImportInserted");
        this.Session.Remove("ImportUpdated");
        this.Session.Remove("ImportUnProcessed");
        this.Session.Remove("ImportDataTable");
    }
}
